<?php
namespace Macaca\Model;

use Monkey;

class Base {

    public
        /**
         * @var \Monkey\App
         */
        $app,
        /**
         * @var \Monkey\Database\Connection
         */
        $conn,
        $table = '', //必须覆写
        $priKey = ''; //必须覆写

    /**
     * @param Monkey\App $app
     */
    public function __construct($app) {
        $this->app = $app;
        $this->conn = $app->database()->getConnection();
    }

    public function find($field, $value) {
        return $this->conn->select($this->table)->where($field, $value)->range(1)->execute()->fetch();
    }

    public function findAll() {
        return $this->conn->select($this->table)->execute()->fetchAll();
    }

    public function delete($field, $value) {
        return $this->conn->delete($this->table)->where($field, $value)->execute()->affected();
    }

    public function insert($data) {
        if (isset($data[$this->priKey])) {
            unset($data[$this->priKey]);
        }

        return $this->conn->insert($this->table)->fields($data)->execute()->lastInsertId();
    }

    public function updateByPriKey($priValue, $data) {
        if (isset($data[$this->priKey])) {
            unset($data[$this->priKey]);
        }

        return $this->conn->update($this->table)
            ->where($this->priKey, $priValue)->set($data)
            ->execute()->affected();
    }

    public function count() {
        $result = $this->conn->select($this->table)->getCountQuery()->execute()->fetch();
        return $result['mk_count_value'];
    }

}